package com.siysoft.util.sms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.siysoft.exception.SMSCodeSendFailedException;

/**
 * <p>
 * Title: SMSSender
 * </p>
 * <p>
 * Description: 短信发送工具类
 * </p>
 * <p>
 * Company: SiySoft
 * </p>
 * 
 * @author liguanghui
 * @date 2015年7月14日
 */
public class SMSSender {
	// 商户账号和密码
	private final static String SMS_ACCOUNT_NUMBER = "xd000516";
	private final static String SMS_PASSWORD = "nlh1016";

	private static String returnstatus;
	private static String message;
	private static String remainpoint;
	private static String taskID;
	private static String successCounts;

	public void sendSMS(String Mobile, String Content) throws Exception {
		URL url = null;
		Document document = null;

		String sendContent = URLEncoder.encode(
				Content.replaceAll("<br/>", " "), "UTF-8");
		// 发送get请求
		url = new URL("http://dx.ipyy.net/sms.aspx?" + "action=send"
				+ "&userid=" + "&account=" + SMS_ACCOUNT_NUMBER
				+ "&password=" + SMS_PASSWORD + "&mobile=" + Mobile
				+ "&content=" + sendContent + "&sendTime=" + "&extno=");
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setRequestMethod("GET");
		con.setDoOutput(true);
		con.setRequestProperty("Pragma:", "no-cache");
		con.setRequestProperty("Cache-Control", "no-cache");
		con.setRequestProperty("Content-Type", "text/xml");

		// 获取返回的xml
		BufferedReader br = new BufferedReader(new InputStreamReader(
				con.getInputStream(), "utf-8"));

		// 解析xml
		SAXReader saxReader = new SAXReader();

		document = saxReader.read(br);
		Element node = document.getRootElement();

		SMSSender.returnstatus = node.elementText("returnstatus");
		SMSSender.message = node.elementText("message");
		SMSSender.remainpoint = node.elementText("remainpoint");
		SMSSender.taskID = node.elementText("taskID");
		SMSSender.successCounts = node.elementText("successCounts");

		if (SMSSender.returnstatus.equals("Faild")) {
			throw new SMSCodeSendFailedException(Mobile,
					SMSSender.remainpoint, SMSSender.message);
		}
	}
}
